package com.scenic.util;


import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;


import java.util.*;
import java.util.regex.Pattern;

/**
 * @author admin
 * @version 1.0 <br/>
 * <p style="font-family:SimSun;font-weight:bold">时间:<br/>2022/3/16 9:31</p>
 */

public class JWTUtils {

    /**过期时间*/
    public static final long EXPIRE = 1000*60*60*24*7;
    /**密钥*/
    public static final String APP_SECRET = "scenic19700791";
    /**根据昵称和角色名获取token*/
    public static String getJwtToken(String username, List<String> roles, String userId, String avatar, String email){
        return Jwts.builder()
                .setHeaderParam("typ", "JWT")
                .setHeaderParam("alg", "HS256")
                .setSubject("scenic")   //存的字符串
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRE))
                .claim("username", username)//存用户名
                .claim("roles", roles)//存用户角色
                //.claim("pet", pet)//存用户昵称
                .claim("userId", userId)//存用户id
                .claim("userAvatar", avatar)//存用户头像
                //.claim("userGender",gender)//存用户描述
                .claim("userEmail", email)
                .signWith(SignatureAlgorithm.HS256, APP_SECRET)//签名
                .compact();
    }

    /**获得请求链
     *因为多处使用，所以抽成方法
     *
     */
    private static Claims getClaims(String jwtToken){
        Jws<Claims> claimsJws = null;
        try {
            claimsJws = Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(jwtToken);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return claimsJws.getBody();
    }

    /**
     * 判断token是否存在与有效
     * @param jwtToken token字符串
     * @return true有效，false无效
     */
    public static boolean checkToken(String username,String jwtToken) {
        if(StringUtils.isEmpty(jwtToken)) return false;
        Claims body = getClaims(jwtToken);
        String username1;
        if (body != null) {
            username1 = (String) body.get("username");
            return username1.equals(username);
        }
        return false;
    }

    /**
     * 检查token
     * @param jwtToken token
     * @return 是否有效
     */
    public static boolean checkToken(String jwtToken) {
        if(StringUtils.isEmpty(jwtToken)) return false;
        Claims body = getClaims(jwtToken);
        return !ObjectUtils.isEmpty(body);
    }

    public static boolean checkFormat(String jwtToken){
        String pattern="[0-9a-zA-Z_-]+\\.[0-9a-zA-Z_-]+\\.[0-9a-zA-Z_-]+";
        return Pattern.matches(pattern, jwtToken);
    }
    /**
     * 解析token
     * @param jwtToken 令牌
     * @return 用户信息
     */
    public static Map<String,Object> getInfo(String jwtToken){
        Map<String,Object> map=new HashMap<>();
        Claims body = getClaims(jwtToken);
        String username = (String) body.get("username");
        List<String> roles =  roles = (List<String>) body.get("roles");
        String avatar= (String) body.get("userAvatar");
        String userId= (String) body.get("userId");
        String userEmail = (String) body.get("userEmail");
        map.put("userEmail",userEmail);
        map.put("username",username);
        map.put("userId", userId);
        map.put("roles",roles);
        map.put("userAvatar",avatar);
        return map;
    }
    //刷新token
    public static String refreshJwtToken(String username,List<String> roles,String pet,
                                         String userId,String photo,String description){
        return Jwts.builder()
                .setHeaderParam("typ", "JWT")
                .setHeaderParam("alg", "HS256")
                .setSubject("blog")   //存的字符串
                .setIssuedAt(new Date())
                .setExpiration(new Date())
                .claim("username", username)//存用户名
                .claim("roles", roles)//存用户角色
                .claim("pet", pet)//存用户昵称
                .claim("userId", userId)//存用户id
                .claim("photo", photo)//存用户头像
                .claim("description",description)//存用户描述
                .signWith(SignatureAlgorithm.HS256, APP_SECRET)//签名
                .compact();
    }

    public static void main(String[] args) {
        String token="eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJzY2VuaWMiLCJpYXQiOjE2NDc3NTU2MjAsImV4cCI6MTY0ODM2MDQyMCwidXNlcm5hbWUiOiJhZG1pbiIsInJvbGVzIjpbImFkbWluIl0sInVzZXJJZCI6IjE1MDUyMDExMTAwNTc1MTcwNTciLCJ1c2VyQXZhdGFyIjoiaHR0cHM6Ly9ibG9naW0ub3NzLWNuLWJlaWppbmcuYWxpeXVuY3MuY29tL215X2ZpbGUvZjQ0OGU1MmItZmJhYy00MmU4LWIxZGUtMTM1M2U5YTg0NzkwLmpwZyIsInVzZXJFbWFpbCI6InoxODE1NTAzODMyMEAxNjMuY29tIn0.cNtjsGvFIUoOKEUJj8ry_xgi8taOhCnR9AmsUuDdBYI";
        Map<String, Object> info = JWTUtils.getInfo(token);
        System.out.println(info);
    }
}